//
//  FJEditViewController.swift
//  FruitJuice
//
//  Created by Rae on 2023/12/21.
//

import UIKit
import ZLPhotoBrowser

class FJEditViewController: FJBaseViewController {

    private let backButton          = c_make_ex(UIButton.self)
        .image("FJ_Profile_back").end()
    private let titleLabel          = c_make_ex(UILabel.self)
        .text("Personal Data").color(.black)
        .font(19.font_bold).end()
    private let nameTextF           = c_make_ex(UITextField.self)
        .bgColor("#EFEFEF").corner(25).font(17.font_medium)
        .placeholder("Enter your nickname").color(.black).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let avatarLabel         = c_make_ex(UILabel.self)
        .color(.black).font(21.font_bold).text("Change avatar").end()
    private let doneButton          = c_make_ex(UIButton.self)
        .bgColor("#FF9133".toColor).corner(25).font(21.font_bold)
        .text("Save").color(.white).end()
    
    private var dataSource: [FJSetupInfoModel] = [
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemOne",select: false,isShowCamera: true),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemTwo",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemThree",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemFour",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemFive",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemSix",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemSeven",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemEight",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemNine",select: false,isShowCamera: false)]
    
    private var selImg: UIImage?
    private var imgUrl: String?
    private var selIndex: Int?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            titleLabel
            nameTextF
            collectionView
            avatarLabel
            doneButton
        }
        
        
        let itemW = (.screenWidth - 55.0)/3
        backButton.top(.statusHeight + 7).leading(15).size(30)
        titleLabel.leading(60)
        titleLabel.CenterY == backButton.CenterY
        nameTextF.width(320).height(50).centerHorizontally()
        nameTextF.Top == backButton.Bottom + 44.0
        collectionView.leading(0).trailing(0).height(itemW*3 + 30)
        collectionView.Top == nameTextF.Bottom + 30.0
        avatarLabel.leading(40)
        avatarLabel.Top == collectionView.Bottom + 15.0
        doneButton.width(320).height(50).centerHorizontally()
        doneButton.Top == collectionView.Bottom + 90.0
        
        nameTextF.style { v in
            v.placehold("#B5B5B5".toColor, font: 17.font_medium)
            let leftImage = UIImageView(image: UIImage(named: "FJ_Profile_Edit_profile"))
            leftImage.frame = CGRect(x: 15, y: 13, width: 24, height: 24)
            let leftV = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
            leftV.addSubview(leftImage)
            v.leftView = leftV
            v.leftViewMode = .always
        }
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12.5, bottom: 0, right: 12.5)
        layout.scrollDirection = .vertical
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(FJAboutYouCollectionItem.self, forCellWithReuseIdentifier: FJAboutYouCollectionItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        
        doneButton.addTarget(self, action: #selector(clickSaveButton), for: .touchUpInside)
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
    }
    
    @objc private func clickSaveButton(){
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func clickBackButton(){
        self.navigationController?.popViewController(animated: true)
    }
}

extension FJEditViewController: UICollectionViewDelegate,UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: FJAboutYouCollectionItem.description(), for: indexPath) as? FJAboutYouCollectionItem else { return UICollectionViewCell() }
        item.itemModel = dataSource[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        selIndex = indexPath.row
        if indexPath.row == 0 {
            //打开相册
            ZLPhotoConfiguration.default()
                .allowSelectVideo(false)
            let ps = ZLPhotoPreviewSheet()
            ps.selectImageBlock = { [weak self] results, isOriginal in
                ToastTool.show()
                let image = results.first?.image
                self?.selImg = image
                var models = [FJSetupInfoModel]()
                self?.dataSource.forEach { model in
                    var itemModel = model
                    models.append(itemModel)
                }
                if let img = image {
                    models[0].image = img
                }
                self?.dataSource = models
                collectionView.reloadData()
                RT.uploadCoverImage(file: (self?.imageToBase64String(image: image!))!) { [weak self] (dict) in
                    ToastTool.dismiss()
                    self?.imgUrl = dict.url!
                }
            }
            ps.showPhotoLibrary(sender: self)
        }
        
        var models = [FJSetupInfoModel]()
        dataSource.forEach { model in
            var itemModel = model
            itemModel.select = false
            models.append(itemModel)
        }
        models[indexPath.row].select = true
        if let img = selImg {
            models[0].image = img
        }
        dataSource = models
        collectionView.reloadData()
    }
}
